package example;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Iterator;

import de.siegmar.fastcsv.reader.CsvReader;
import de.siegmar.fastcsv.reader.CsvRecord;

/// Example for reading CSV data from a file in the classpath.
public class ExampleCsvReaderWithClasspathInput {

    // public static void main(final String[] args) throws IOException {
    //     try (CsvReader<CsvRecord> csv = CsvReader.builder().ofCsvRecord(readFromClasspath("/resources/example.csv"))) {
    //         csv.forEach(System.out::println);
    //         csv.iterator().forEachRemaining(record -> {
    //             for (int i = 0; i < record.getFieldCount(); i++) {
    //                 System.out.println("Field " + i + ": " + record.getField(i));
    //             }
    //         });
    //     }
    // }

    // public static void main(String[] args) {
    //     String messy = "乱码的字符串";
    //     byte[] bytes = messy.getBytes();
    //     System.out.println("字节序列: " + Arrays.toString(bytes));
    // }

    public static void main(final String[] args) throws IOException {
        try (CsvReader<CsvRecord> csv = CsvReader.builder()
                .ofCsvRecord(readFromClasspath("/resources/example.csv"))) {

            // 获取迭代器用于遍历记录
            Iterator<CsvRecord> iterator = csv.iterator();
            
            // 行索引从0开始：第二行的索引是1
            int targetRowIndex = 1;
            // 列索引从0开始：第三列的索引是2
            int targetColumnIndex = 2;
            
            int currentRowIndex = 0;
            String targetValue = null;
            
            // 遍历CSV记录，寻找目标行
            while (iterator.hasNext()) {
                CsvRecord record = iterator.next();
                
                // 找到目标行
                if (currentRowIndex == targetRowIndex) {
                    // 检查列索引是否有效
                    if (targetColumnIndex < record.getFieldCount()) {
                        targetValue = record.getField(targetColumnIndex);
                    } else {
                        targetValue = "目标列索引超出范围";
                    }
                    break; // 找到后退出循环
                }
                
                currentRowIndex++;
            }
            
            // 输出结果
            if (targetValue != null) {
                System.out.printf("第二行第三列的值: %s%n", targetValue);
            } else {
                System.out.println("未找到目标行");
            }
        }
    }

    static InputStream readFromClasspath(final String name) throws FileNotFoundException {
        final InputStream in = ExampleCsvReaderWithClasspathInput.class.getResourceAsStream(name);
        if (in == null) {
            throw new FileNotFoundException("Resource not found on classpath: " + name);
        }
        return in;
    }

}
